const koa = require("koa")
const app = new koa();
const router = require("koa-router")()
const main = require("./models")
const koaBody = require("koa-body")
const path = require("path");
const fs = require("fs");
const static = require("koa-static");
router.get("/find", async ctx => {
    
    var collection = await main();
    var result = await collection.find().toArray();
    ctx.body = result
    console.log(result);
})
router.get("/add", async ctx => {
    var collection = await main();
    var obj = {
        name: "liao",
        age: 19
    }
    var res = await collection.find({ name: obj.name }).toArray();
    if (res.length) {
        ctx.body = "数据库已存在这条数据"
    }
    else {
        var result = await collection.insertOne(obj)
        console.log(result);
    }
})
router.post("/doForm",async ctx=>{
    console.log(ctx.request.files);
    var {name,age} = ctx.request.body;
    age = Number(age)
    var filename = ctx.request.files.logo.path;
    var reader = fs.createReadStream(filename);
    var uploadFile = `./static/${path.basename(filename)}`;
    var write = fs.createWriteStream(uploadFile);
    reader.pipe(write);
    var logo = ctx.origin+"/"+path.basename(filename);
    console.log(logo);
    const collection = await main();
    await collection.insertOne({name,age,logo});
    await ctx.redirect("/find")
})
app.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 200 * 1024 * 1024, 
		keepExtensions: true
    }
}))
app.use(static(path.join(__dirname,"static")))
app.use(async (ctx,next)=>{
    ctx.set("Access-Control-Allow-Origin","*")
    await next()
})

app.use(router.routes())
app.listen(8080)